package com.googlecode.c4e.ui.views;

import java.util.Iterator;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.ui.part.ViewPart;

import com.googlecode.c4e.api.Registry;
import com.googlecode.c4e.api.model.Project;
import com.googlecode.c4e.api.model.ProjectGroup;
import com.googlecode.c4e.api.model.Server;
import com.googlecode.c4e.ui.views.internal.ElementComparator;
import com.googlecode.c4e.ui.views.internal.ViewLayoutChangeAction;
import com.googlecode.c4e.ui.wizards.AddServerWizard;

public class ServersView extends ViewPart implements ISelectionListener {

	public static final String FLAT = "Flat";
	public static final String TREE = "Tree";
	private TreeViewer viewer;
	private Action refreshAction;
	private Action addServerAction;

	/**
	 * This is a callback that will allow us to create the viewer and initialize
	 * it.
	 */
	public void createPartControl(Composite parent) {
		viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
		viewer.setContentProvider(new ServersContentProvider());
		viewer.setLabelProvider(new WorkbenchLabelProvider());
		viewer.setInput(getViewSite());
		viewer.setComparator(new ViewerComparator(new ElementComparator()));

		// Create the help context id for the viewer's control
		makeActions();
		hookContextMenu();
		hookDoubleClickAction();
		contributeToActionBars();

		getSite().setSelectionProvider(viewer);
		getSite().getWorkbenchWindow().getSelectionService()
				.addPostSelectionListener(this);
	}

	private void hookContextMenu() {
		MenuManager menuMgr = new MenuManager("#PopupMenu");
		menuMgr.setRemoveAllWhenShown(true);
		menuMgr.addMenuListener(new IMenuListener() {
			public void menuAboutToShow(IMenuManager manager) {
				ServersView.this.fillContextMenu(manager);
			}
		});
		Menu menu = menuMgr.createContextMenu(viewer.getControl());
		viewer.getControl().setMenu(menu);
		getSite().registerContextMenu(menuMgr, viewer);
	}

	private void contributeToActionBars() {
		IActionBars bars = getViewSite().getActionBars();
		IMenuManager actionBarsMenu = bars.getMenuManager();
		// actionBarsMenu.add(new BooleanPropertyAction("Presentation",
		// ContinuumPlugin.getDefault().getPreferenceStore(), ""));

		fillLocalPullDown(bars.getMenuManager());
		fillLocalToolBar(bars.getToolBarManager());
	}

	private void fillLocalPullDown(IMenuManager manager) {
		manager.add(new Separator());
		IMenuManager presentation = new MenuManager("Presentation");
		manager.add(presentation);
		presentation.add(new ViewLayoutChangeAction(this, ServersView.TREE));
		presentation.add(new ViewLayoutChangeAction(this, ServersView.FLAT));
		// manager.add(action2);
	}

	private void fillContextMenu(IMenuManager manager) {
		manager.add(refreshAction);
		manager.add(addServerAction);
		manager.add(new Separator());
		// drillDownAdapter.addNavigationActions(manager);
		// Other plug-ins can contribute there actions here
		manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
	}

	private void fillLocalToolBar(IToolBarManager manager) {
		// manager.add(buildAction);
		// manager.add(action2);
		manager.add(new Separator());
		// drillDownAdapter.addNavigationActions(manager);
	}

	private void makeActions() {
		refreshAction = new Action("Refresh") {
			public void run() {
				refreshViewerNode();
				addServerAction.setEnabled(Registry.getDefault()
						.isContinuumConnectorAvailable());
			}
		};
		addServerAction = new Action("Add Server...") {
			public void run() {
				Wizard wizard = new AddServerWizard();
				Shell shell = PlatformUI.getWorkbench()
						.getActiveWorkbenchWindow().getShell();
				WizardDialog dialog = new WizardDialog(shell, wizard);

				dialog.open();
			}
		};
		addServerAction.setEnabled(Registry.getDefault()
				.isContinuumConnectorAvailable());
	}

	public void refreshViewer() {
		if (viewer == null) {
			return;
		} else {
			viewer.refresh();
		}
	}

	@SuppressWarnings("unchecked")
	public void refreshViewerNode() {
		IStructuredSelection selection = (IStructuredSelection) viewer
				.getSelection();
		Iterator iter = selection.iterator();
		while (iter.hasNext()) {
			Object object = iter.next();
			if (object instanceof Server) {
				Server server = (Server) object;
				server.setProjectGroups(null);
				viewer.refresh(object);
				break;
			}
			if (object instanceof ProjectGroup) {
				ProjectGroup group = (ProjectGroup) object;
				group.setProjects(null);
				viewer.refresh(object);
				break;
			}
			if (object instanceof Project) {
				Project project = (Project) object;
				project.setState(null);
				viewer.refresh(object);
				break;
			}
			viewer.refresh(object);
		}
	}

	private void hookDoubleClickAction() {
		// viewer.addDoubleClickListener(new IDoubleClickListener() {
		// public void doubleClick(DoubleClickEvent event) {
		// doubleClickAction.run();
		// }
		// });
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
		viewer.getControl().setFocus();
	}

	public void selectionChanged(IWorkbenchPart part, ISelection selection) {
		getViewSite().getActionBars().getStatusLineManager().setMessage(
				getStatusLineMessage(selection));
	}

	private String getStatusLineMessage(ISelection selection) {
		if (selection == null || selection.isEmpty()
				|| !(selection instanceof IStructuredSelection)) {
			return "";
		}
		IStructuredSelection s = (IStructuredSelection) selection;

		if (s.size() > 1) {
			return "";
		}
		return s.getFirstElement().toString();
	}
}